package eerbaar.server.gamebuilder.config;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import eerbaar.server.gamebuilder.IConfig;

public abstract class AbstractConfig implements IConfig {

    private void assign(final String name, final Object value) {

        Method target = null;

        Method[] methods = this.getClass().getDeclaredMethods();
        for (Method method : methods) {
            String test = method.getName();
            if (test.equalsIgnoreCase("set" + name)) {
                target = method;
                break;
            }
            if (test.equalsIgnoreCase("add" + name)) {
                target = method;
                break;
            }
        }

        if (target == null) {
            String msg = name + " not found on "
                    + this.getClass().getSimpleName();
            assert (false) : msg;
            System.out.println(msg);
            return;
        }

        try {
            Class<?> clazz = target.getParameterTypes()[0];
            if (clazz.getName().equals("int")) {
                target.invoke(this, Integer.parseInt((String) value));
            } else if (clazz.getName().equals("java.lang.String")) {
                target.invoke(this, (String) value);
            } else {
                target.invoke(this, clazz.cast(value));
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassCastException e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void setConfig(String name, IConfig config) {

        assign(name, config);
    }

    @Override
    public void setProperty(final String name, final Object value) {

        assign(name, value);
    }
}
